﻿using DBHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;

namespace Creator.Core.Log
{
    public class LogDB : GetDBBase
    {
        object lockObject = new object();
        const string DB_PATH = @"d:\data\SysData.db";
        public LogDB() : base( DBType.Sqllite, DB_PATH)
        {
            bool needCreate = File.Exists(DB_PATH);
            TestConnected();
            if (!needCreate)
            {
                //创建表
                string tab = @"CREATE TABLE T_Log (
                                id    INTEGER         PRIMARY KEY AUTOINCREMENT,
                                Device varchar(255),
                                Info  VARCHAR (555),
                                Time  TIME,
                                Level INTEGER
                            );";

                db.ExecNonQuery(tab);
            }
        }

        public List<T_Log> GetLogs(string device = null, DateTime? startTime = null,DateTime? endTime = null ,LogLevel? level = null)
        {
            string sql = "select * from T_Log where 1=1 ";
            if (startTime != null)
            {
                sql += $" and time >={startTime}";
            }
            if (endTime != null)
            {
                sql += $" and time <={endTime}";
            }
            if (level != null)
            {
                sql += $" and level ={level}";
            }
            if (device != null)
            {
                sql += $" and Device ={device}";
            }
            return db.GetDataList<T_Log>(sql);
        }
         
        public bool AddLog(string info,LogLevel level)
        {
            lock (lockObject)
            {
                string sql = $"insert into t_log(Device,info,time,level ) values('A1001','{info}',datetime('now'),{level});";
                return db.ExecNonQuery(sql) > 0;
            } 
        }

        public bool AddLogs(List<T_Log> logs)
        {
            lock (lockObject)
            {
                StringBuilder sb = new StringBuilder();
                foreach (T_Log log in logs)
                {
                    sb.Append($"insert into t_log(info,time,level ) values('{log.Info}',datetime('now'),{log.Level});");
                }
                return db.ExecNonQueryTrans(sb.ToString()) > 0;
            }
        }
    }

    public class T_Log
    {
        internal int ID { get; set; }
        public string Device { get; set; }
        public string Info { get; set; }
        public DateTime Time { get; set; }
        public LogLevel Level { get; set; }
    }
}
